<template>
  <div class="color-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>颜色管理</h1>
          <el-button type="primary" @click="openAdd">新增颜色</el-button>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索颜色名称"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="filterColors">搜索</el-button>
            <el-button :disabled="!selected.length" @click="batchEnable">批量启用</el-button>
            <el-button :disabled="!selected.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table :data="paginatedColors" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="颜色名称" prop="colorName" />
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status == 1 || row.status === '1' ? 'success' : 'info'">{{
                  row.status == 1 || row.status === '1' ? '启用' : '禁用'
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row.colorId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>

    <el-dialog
      :title="editing ? '编辑颜色' : '新增颜色'"
      :model-value="dialogVisible"
      width="520px"
      @close="closeDialog"
    >
      <el-form :model="form" label-width="90px">
        <el-form-item label="名称" required>
          <el-input v-model="form.colorName" placeholder="请输入颜色名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productService } from '@/api'

type ColorRow = { colorId?: number; colorName: string; status: number | string; remarks?: string }

const loading = ref(false)
const colors = ref<ColorRow[]>([])
const selected = ref<ColorRow[]>([])
const total = ref(0)

const dialogVisible = ref(false)
const editing = ref(false)
const editingId = ref<number | null>(null)
const form = ref<ColorRow>({ colorName: '', status: 1, remarks: '' })
// 分页相关状态
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 过滤后的颜色列表
const paginatedColors = computed(() => {
  return colors.value
})

const loadList = async () => {
  loading.value = true
  try {
    const res = await productService.getColorsListPage(page.value, pageSize.value, keyword.value || undefined, undefined)
    if (res.data.code === 200) {
      const data = res.data.data
      if (data) {
        colors.value = data.list || []
        total.value = data.total || 0
      }
    }
  } finally {
    loading.value = false
  }
}

const openAdd = () => {
  editing.value = false
  editingId.value = null
  form.value = { colorName: '', status: 1, remarks: '' }
  dialogVisible.value = true
}

const openEdit = (row: ColorRow) => {
  editing.value = true
  editingId.value = row.colorId || null
  form.value = {
    colorName: row.colorName,
    status: typeof row.status === 'string' ? parseInt(row.status) : row.status,
    remarks: row.remarks || '',
  }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const submit = async () => {
  if (!form.value.colorName.trim()) {
    ElMessage.error('请输入颜色名称')
    return
  }

  try {
    const submitData = {
      ...form.value,
      status: form.value.status.toString(),
    }

    if (editing.value && editingId.value) {
      await productService.updateColor(editingId.value, submitData as any)
      ElMessage.success('更新颜色成功')
    } else {
      await productService.addColor(submitData as any)
      ElMessage.success('添加颜色成功')
    }
    dialogVisible.value = false
    loadList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(editing.value ? '更新颜色失败' : '添加颜色失败')
  }
}

const handleDelete = async (id?: number) => {
  if (!id) return

  try {
    await ElMessageBox.confirm('确定要删除这个颜色吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await productService.deleteColor(id)
    ElMessage.success('删除颜色成功')
    loadList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除颜色失败')
    }
  }
}

const handleSelectionChange = (rows: ColorRow[]) => {
  selected.value = rows
}

const batchEnable = async () => {
  if (!selected.value.length) return
  try {
    await Promise.all(
      selected.value.map(
        (item) =>
          item.colorId &&
          productService.updateColor(item.colorId, {
            colorName: item.colorName,
            status: '1',
            remarks: item.remarks || '',
          } as any),
      ),
    )
    ElMessage.success('批量启用成功')
    selected.value = []
    await loadList()
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error('批量启用失败')
  }
}

const batchDisable = async () => {
  if (!selected.value.length) return
  try {
    await Promise.all(
      selected.value.map(
        (item) =>
          item.colorId &&
          productService.updateColor(item.colorId, {
            colorName: item.colorName,
            status: '0',
            remarks: item.remarks || '',
          } as any),
      ),
    )
    ElMessage.success('批量禁用成功')
    selected.value = []
    await loadList()
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error('批量禁用失败')
  }
}

const batchDelete = async () => {
  if (!selected.value.length) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selected.value.length} 个颜色吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    await Promise.all(
      selected.value.map((item) => item.colorId && productService.deleteColor(item.colorId)),
    )
    ElMessage.success('批量删除成功')
    selected.value = []
    await loadList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页处理函数
const filterColors = () => {
  page.value = 1 // 搜索时重置到第一页
  loadList()
}

const handlePageChange = (val: number) => {
  page.value = val
  loadList()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  page.value = 1 // 每页大小改变时重置到第一页
  loadList()
}

onMounted(loadList)
</script>

<style scoped>
.color-manage {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.toolbar {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.pager {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
